package com.kzw.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import my.db.QueryHelper;

import com.kzw.bean.Record;
import com.kzw.dao.support.Page;
import com.kzw.entity.Article;
import com.kzw.entity.Dictionary;

/**
 * 针对某一个实体对应表的增删改查
 * 	单个表的增删改查，和业务没有关系
 * */
public class ArticleDao {

	/**
	 * 增加
	 * */
	public void save(Article article) {
		String sql = "insert into article values(null,?,?,?,?,?)";
		QueryHelper.update(sql, article.getTitle(), article.getCtime(), article.getTypeId(), article.getTitlePic(), article.getContent());
	}
	
	/**
	 * 修改
	 * */
	public void update(Article article) {
		String sql = "update article set title=?, ctime=?, typeId=?, titlePic=?, content=? where id=?";
		QueryHelper.update(sql, article.getTitle(), article.getCtime(), article.getTypeId(), article.getTitlePic(), article.getContent(), article.getId());
	}
	
	/**
	 * 删除
	 * */
	public void remove(Long id) {
		String sql = "delete from article where id=?";
		QueryHelper.update(sql, id);
	}
	
	/**
	 * 根据ID查询
	 * */
	public Article findById(Long id) {
		String sql = "select * from article where id=?";
		Article article = QueryHelper.queryUnique(Article.class, sql, id);
		QueryHelper.load(article, "type", "typeId", Dictionary.class);
		
		return article;
	}
	
	/**
	 * 查询所有
	 * */
	public List<Article> findAll() {
		String sql = "select * from article";
		List<Article> list = QueryHelper.query(Article.class, sql);
		QueryHelper.load(list, "type", "typeId", Dictionary.class);
		
		return list;
	}

	/**
	 * 分页查找
	 * */
	public Record findPage(Page<Article> page) {
		Record record = new Record();
		String sql = "select * from article";
		if(StringUtils.isNotBlank(page.getOrderBy())) {
			sql += String.format(" order by %s %s", page.getOrderBy(), page.getOrder());
		}
		
		List<Article> list = QueryHelper.queryPage(Article.class, sql, page.getPageNo(), page.getPageSize());
		QueryHelper.load(list, "type", "typeId", Dictionary.class);
		
		String sql2 = sql.toLowerCase().replaceFirst("select .*? from", "select count(*) from");
		long count = QueryHelper.stat(sql2);
		
		record.setCount(count);
		record.setData(list);
		
		return record;
	}

	/**
	 * 批量删除
	 * */
	public void multiDel(String ids) {
		String sql = "delete from article where id in (" + ids + ")";
		QueryHelper.update(sql);
	}
}
